package br.brpv.silvestrin.vendas.mainactivity;

//TODO Salvar pesquisa quando muda de aba
//TODO quando muda de aba e volta, a está salvando a pesquisa dos itemcfg e colocando ela na pesquisa dos itens também
//TODO quando muda de aba e volta, o nome do item selecionado está vazio

import java.util.ArrayList;

import android.content.*;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.SearchView.OnCloseListener;
import android.widget.SearchView.OnQueryTextListener;
import br.brpv.silvestrin.vendas.R;
import br.brpv.silvestrin.vendas.domain.*;
import br.brpv.silvestrin.vendas.listeners.ItemsQueryListener;
import br.brpv.silvestrin.vendas.manager.ItemsManager;
import br.brpv.silvestrin.vendas.util.ShowMessage;
import br.brpv.silvestrin.vendas.webservice.ServerConnection;
import br.brpv.silvestrin.vendas.webservice.ServerDataCacheService;

public class StockFragment extends CompanyFragment implements ItemsManager.ItemsFromServerListener {
    private static final String SAVE_ITEMS_LIST = "saveItemList";
    private static final String SAVE_SEARCH_OPTION = "searchOptionSaved";
    private static final String SAVE_COD_COMPANY = "saveCodCompany";

    private ItemAdapter adapterItems = null;
    private ItemCfgAdapter adapterItemsCfg = null;
    private String queryItemsText = "";
    private String queryItemsCfgText = "";

    private String codPriceTable = "0"; //2072

    private Item selectedItem = null;

    private ServerDataCacheService mServerDataCacheBinder;
    private boolean mBound;
    private TextView totalStock;
    private CheckBox stockCheckBox;
    private ItemsManager itemsManager;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //bind on ServerDataCacheService
        Intent intent = new Intent(getActivity(), ServerDataCacheService.class);
        getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);


        adapterItemsCfg =
                new ItemCfgAdapter(getActivity(),R.layout.list_view_rows_itens_details, new ArrayList<ItemCfg>());
        itemsManager = new ItemsManager(getActivity(), this);

        if(savedInstanceState != null) {
            loadSavedItemList(savedInstanceState);
        } else {
            itemsManager.requestItems(codSelectedCompany);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.stock_layout, container, false);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        ListView itemsList = (ListView)getActivity().findViewById(R.id.listItens);
        if(itemsList != null) {
            itemsList.setAdapter(adapterItems);
            itemsList.setOnItemClickListener(new ItemListClickListener(this));
            itemsList.setDrawSelectorOnTop(true);
        }

        ListView itemsCfgList = (ListView)getActivity().findViewById(R.id.list_cfg_items);
        if(itemsCfgList != null){
            itemsCfgList.setAdapter(adapterItemsCfg);
        }


        stockCheckBox = (CheckBox)getActivity().findViewById(R.id.stock_itens);
        if(stockCheckBox != null){
            stockCheckBox.setChecked(true);
            stockCheckBox.setOnClickListener(new checkBoxStockItemListener());
        }

        SearchView searchItemCfg = (SearchView)  getActivity().findViewById(R.id.search_detailed_item);
        if(searchItemCfg != null) {
            QueryItemCfgListener queryItemCfgListener = new QueryItemCfgListener();
            searchItemCfg.setOnQueryTextListener(queryItemCfgListener);
            searchItemCfg.setOnCloseListener(queryItemCfgListener);
            searchItemCfg.setQuery(queryItemsCfgText, false);
        }

        SearchView searchItem = (SearchView) getActivity().findViewById(R.id.search_item);
        if(searchItem != null){
	        QueryItemListener queryItem = new QueryItemListener();
	        searchItem.setOnQueryTextListener(queryItem);
	        searchItem.setOnCloseListener(queryItem);
	        searchItem.setQuery(queryItemsText, false);
        }

        totalStock = (TextView) getActivity().findViewById(R.id.total_in_stock_value);
        adapterItemsCfg.setViewToShowStockSum(totalStock);

        super.onActivityCreated(savedInstanceState);
    }



    @Override
    public void onSaveInstanceState(Bundle outState) {

        ArrayList<Item> itemArray = new ArrayList<Item>();
        for(int i = 0; i < adapterItems.getCount(); i++) {
            itemArray.add(adapterItems.getItem(i));
        }

        outState.putParcelableArrayList(SAVE_ITEMS_LIST, itemArray);
        outState.putInt(SAVE_COD_COMPANY, codSelectedCompany);

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (mBound) {
            getActivity().unbindService(mConnection);
            mBound = false;
        }
    }


    private ServiceConnection mConnection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            ServerDataCacheService.LocalBinder localBinder = (ServerDataCacheService.LocalBinder)iBinder;

            mServerDataCacheBinder = localBinder.getService();
            itemsManager.setmServerDataCacheBinder(mServerDataCacheBinder);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
        }
    };

    public void loadSavedItemList(Bundle savedInstanceState){
        if(savedInstanceState != null) {
            ArrayList<Parcelable> savedArray = savedInstanceState.getParcelableArrayList(SAVE_ITEMS_LIST);
            ArrayList<Item> itemArray = new ArrayList<Item>();

            for(Parcelable p: savedArray) {
                itemArray.add((Item) p);
            }

            codSelectedCompany = savedInstanceState.getInt(SAVE_COD_COMPANY);

            updateItemList(itemArray);
        }
    }

    public void updateItemList(ArrayList<Item> items) {
        if(mServerDataCacheBinder != null) mServerDataCacheBinder.addItemListToCompany(codSelectedCompany, items);
        adapterItems = new ItemAdapter(getActivity(), R.layout.list_view_row_items, items);

        ListView itemsList = (ListView)getActivity().findViewById(R.id.listItens);
        if(itemsList != null) {
            itemsList.setAdapter(adapterItems);
            adapterItems.notifyDataSetChanged();
        }

        adapterItemsCfg.clear();
        adapterItemsCfg.notifyDataSetChanged();
        TextView itemName = (TextView)getActivity().findViewById(R.id.item_selected);
        if(itemName != null) itemName.setText("");

        SearchView searchItem = (SearchView) getActivity().findViewById(R.id.search_item);
        if(searchItem != null) searchItem.setQuery(queryItemsText, false);
    }

    private void updateTotalStocktextView(){
        TextView totalStock = (TextView) getActivity().findViewById(R.id.total_in_stock_value);
        totalStock.setText(String.valueOf(adapterItemsCfg.getStockSum()));
    }

    /*****WEB SERVICE CALLBACKS***/


    @Override
    public void failOnItemsRetrieve() {
        ShowMessage.alertDialog2(getActivity(), R.string.stockfragment_failonretrieveitems,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case DialogInterface.BUTTON_NEGATIVE:
                                getActivity().finish();
                                break;
                            case DialogInterface.BUTTON_POSITIVE:
                                itemsManager.requestItems(codSelectedCompany);
                                break;
                        }
                    }
                });
    }

    @Override
    public void onItemsRetrieve(ArrayList<Item> items) {
        updateItemList(items);
    }

    @Override
    public void failOnItemsCfgRetrieve() {
        ShowMessage.alertDialog2(getActivity(), R.string.stockfragment_failonretrieveitemscfg,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch(which) {
                            case DialogInterface.BUTTON_NEGATIVE:
                                break;
                            case DialogInterface.BUTTON_POSITIVE:
                                if(selectedItem != null) {
                                    refreshItemsCfgScreen();
                                }
                                break;
                        }
                    }
                });
    }

    @Override
    public void onItemsCfgRetrieve(ArrayList<ItemCfg> items) {
        adapterItemsCfg.clear();
        adapterItemsCfg.addAll(items);
        adapterItemsCfg.notifyDataSetChanged();

        updateTotalStocktextView();
    }

    @Override
    public void failOnRetrieveItemCfgPrice() {

    }

    @Override
    public void onItemCfgPriceRetrieve(double value) {
    }


    /****************************/

    /*********LISTENERS***********/
    private class ItemListClickListener implements AdapterView.OnItemClickListener{
        private StockFragment stockFragment;
        private CheckBox stock;
        //private ArrayAdapter<Item> adapterItems = null;

        public ItemListClickListener(StockFragment sf){
            stockFragment = sf;
            stock = (CheckBox)getActivity().findViewById(R.id.stock_itens);
        }
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if(adapterItems.getCount() >= i) {
                stockFragment.setSelectedItem(adapterItems.getItem(i));
                refreshItemsCfgScreen();
            }
        }
    }

    private class checkBoxStockItemListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {

            if(selectedItem != null){
                refreshItemsCfgScreen();
            }
        }
    }

    private class QueryItemCfgListener implements OnQueryTextListener, OnCloseListener {
        @Override
        public boolean onQueryTextSubmit(String s) {
            queryItemsCfgText = s;
            showResults(s);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            showResults(s);
            return false;
        }

        private void showResults(String query) {
            if(adapterItemsCfg != null){
                adapterItemsCfg.getFilter().filter(query);
                updateTotalStocktextView();
            }
        }

        @Override
        public boolean onClose() {
            showResults("");
            return false;
        }
    }

    private class QueryItemListener implements OnQueryTextListener, OnCloseListener {
        @Override
        public boolean onQueryTextChange(String newText) {

            queryItemsText = newText;
            showResults(newText);
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            showResults(query);
            return false;
        }

        private void showResults(String query) {
            if(adapterItems != null) adapterItems.getFilter().filter(query);
        }

        @Override
        public boolean onClose() {
            showResults("");
            return false;
        }
    }
    /*****************************/

    /*****Getters and Setters*****/
    public Item getSelectedItem() {
        return selectedItem;
    }

    public void setSelectedItem(Item selectedItem) {
        TextView itemName = (TextView)getActivity().findViewById(R.id.item_selected);
        itemName.setText(selectedItem.getName());
    	
        this.selectedItem = selectedItem;
    }

    public void setSelectedCompany(int codSelectedCompany) {
        ArrayList<Item> itemsList = null;

        if(codSelectedCompany != this.codSelectedCompany){
            //se o fragmento nao foi inicializado nao chama o servidor pois sera chamado no OnCreate
            if(this.codSelectedCompany == -1) this.codSelectedCompany = codSelectedCompany;
            else {
                this.codSelectedCompany = codSelectedCompany;
                //look at cache for this company items list
                if(mServerDataCacheBinder != null) itemsList =  mServerDataCacheBinder.getItemList(codSelectedCompany);
                //if there is no item list for this company in cache get it from server
                if(itemsList == null || itemsList.size() == 0) itemsManager.requestItems(codSelectedCompany);
                //set list
                else updateItemList(itemsList);
            }
        }
    }

    @Override
    public int getSelectedCompany() {
        return codSelectedCompany;  //To change body of implemented methods use File | Settings | File Templates.
    }

	@Override
	public void refresh() {
	}

    private void refreshItemsCfgScreen(){
        boolean inStock = stockCheckBox.isChecked();
        if(selectedItem != null) {
            itemsManager.requestItemsCfg(selectedItem.getCodItem(), codSelectedCompany, inStock, codPriceTable);
        }
    }

    /*****************************/

}


